import 'dart:io';

import 'package:flutter/material.dart';
import 'package:zpub_bas/zpub_bas.dart';
import 'package:zpub_ui/com/zerogis/zpubui/tree/bean/node.dart';
import 'package:zpub_ui/com/zerogis/zpubui/tree/constant/TreeConstant.dart';

///支持搜索功能
class SearchBar extends StatefulWidget
{
  final List<Node> mList;
  final Function mOnResult;

  SearchBar(this.mList, this.mOnResult);

  @override
  State<StatefulWidget> createState()
  {
    return SearchBarState();
  }
}

class SearchBarState extends State<SearchBar>
{
  static bool _mDelOff = true; //是否展示删除按钮
  static String _mKey = ""; //搜索的关键字

  @override
  Widget build(BuildContext context)
  {
    return Material(
      child: Container(
        width: double.infinity,
        height: 50,
        color: Colors.white,
        padding: EdgeInsets.all(5),
        child: TextField(
          decoration: InputDecoration(
              border: OutlineInputBorder(
                borderSide: BorderSide(color: Colors.white),),
              prefixIcon: Icon(
                Icons.search,
                color: Colors.grey,
              ),
              fillColor: Colors.white,
              filled: true,
              contentPadding: EdgeInsets.all(8),
              suffixIcon: GestureDetector(
                child: Offstage(
                  offstage: _mDelOff,
                  child: Icon(
                    Icons.highlight_off,
                    color: Colors.grey,
                  ),
                ),
                onTap: ()
                {
                  setState(()
                  {
                    _mKey = "";
                    search(_mKey);
                  });
                },
              )),
          controller: TextEditingController.fromValue(
            TextEditingValue(
              text: _mKey,
              selection: TextSelection.fromPosition(
                TextPosition(
                  offset: _mKey == null ? 0 : _mKey.length, //保证光标在最后
                ),
              ),
            ),
          ),
          onChanged: (Platform.isIOS || Platform.isMacOS) ? null : search,
          onSubmitted: (Platform.isIOS || Platform.isMacOS) ? (text)
          {
            search(text);
          } : null,
        ),
      ),
    );
  }

  ///关键字查找
  void search(String value)
  {
    _mKey = value;
    List<Node> tmp = List();
    if (value.isEmpty)
    { //如果关键字为空，代表全匹配
      _mDelOff = true;
      widget.mOnResult(null);
    }
    else
    { //如果有关键字，那么就去查找关键字
      _mDelOff = false;
      for (Node n in widget.mList)
      {
        String name = n.mObject[TreeConstant.NAMEC];
        if (CxTextUtil.isEmpty(name))
        {
          name = n.mObject[TreeConstant.NAME];
        }
        if (name.toLowerCase().contains(value.toLowerCase()))
        { //匹配大小写
          tmp.add(n);
        }
      }
      widget.mOnResult(tmp);
    }
  }
}
